from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from teacher.models import Teacher
from department.models import Department

# Create your views here.

# 教师列表序列化器
class TeacherListSerializer(serializers.ModelSerializer):
    department_name = serializers.CharField(source='department.name', read_only=True)
    
    class Meta:
        model = Teacher
        fields = ['id', 'name', 'sex', 'title', 'department_name']

# 教师创建/更新序列化器
class TeacherCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ['id', 'name', 'sex', 'title', 'department']

# 教师管理视图
class TeacherManagementView(APIView):
    """教师管理相关接口"""
    
    def get(self, request, teacher_id=None):
        """获取教师列表（支持按部门筛选）或单个教师详情"""
        try:
            if teacher_id:
                # 获取单个教师详情
                teacher = Teacher.objects.filter(id=teacher_id).first()
                if not teacher:
                    res = {
                        'status': 404,
                        'data': {
                            'message': '教师不存在'
                        }
                    }
                    return Response(res, status=status.HTTP_404_NOT_FOUND)
                
                serializer = TeacherListSerializer(teacher)
                res = {
                    'status': 200,
                    'data': {
                        'teacher': serializer.data,
                        'message': '教师详情获取成功'
                    }
                }
            else:
                # 获取查询参数
                department_id = request.query_params.get('department_id')
                
                # 构建查询条件
                teachers = Teacher.objects.all()
                
                if department_id:
                    # 验证部门是否存在
                    department = Department.objects.filter(id=department_id).first()
                    if not department:
                        res = {
                            'status': 404,
                            'data': {
                                'total': 0,
                                'list': [],
                                'message': '部门不存在'
                            }
                        }
                        return Response(res, status=status.HTTP_404_NOT_FOUND)
                    
                    teachers = teachers.filter(department_id=department_id)
                
                # 序列化数据
                serializer = TeacherListSerializer(teachers, many=True)
                
                # 构建响应
                res = {
                    'status': 200,
                    'data': {
                        'total': teachers.count(),
                        'list': serializer.data,
                        'message': '教师列表获取成功'
                    }
                }
            return Response(res, status=status.HTTP_200_OK)
            
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request):
        """创建新教师"""
        try:
            serializer = TeacherCreateUpdateSerializer(data=request.data)
            if serializer.is_valid():
                teacher = serializer.save()
                res = {
                    'status': 201,
                    'data': {
                        'id': teacher.id,
                        'message': '教师创建成功'
                    }
                }
                return Response(res, status=status.HTTP_201_CREATED)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def put(self, request, teacher_id=None):
        """更新教师信息"""
        try:
            if not teacher_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '教师ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            teacher = Teacher.objects.filter(id=teacher_id).first()
            if not teacher:
                res = {
                    'status': 404,
                    'data': {
                        'message': '教师不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            serializer = TeacherCreateUpdateSerializer(teacher, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                res = {
                    'status': 200,
                    'data': {
                        'message': '教师更新成功'
                    }
                }
                return Response(res, status=status.HTTP_200_OK)
            else:
                res = {
                    'status': 400,
                    'data': {
                        'message': '数据验证失败',
                        'errors': serializer.errors
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, teacher_id=None):
        """删除教师"""
        try:
            if not teacher_id:
                res = {
                    'status': 400,
                    'data': {
                        'message': '教师ID不能为空'
                    }
                }
                return Response(res, status=status.HTTP_400_BAD_REQUEST)
            
            teacher = Teacher.objects.filter(id=teacher_id).first()
            if not teacher:
                res = {
                    'status': 404,
                    'data': {
                        'message': '教师不存在'
                    }
                }
                return Response(res, status=status.HTTP_404_NOT_FOUND)
            
            teacher.delete()
            res = {
                'status': 200,
                'data': {
                    'message': '教师删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 500,
                'data': {
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
